import {get, post} from '../utils/saveApi/utils';
import { ref } from "vue";
let saveFlag = ref(0);
// 定义 mixin 函数，接受泛型参数 T，表示当前模块中的方法类型
const useSaveFlag = <T extends Function>(dialogAddSave?: T, dialogAddSaveTwo?: T) => {
    // export const saveFlag = function(){
    let firstSave=(key:string, fun?:()=>{})=>{
        if(saveFlag.value != 0){
            return false;
        }else{
            ++saveFlag.value; 
            if(key=='two'){
                dialogAddSaveTwo();
            }else{
                dialogAddSave();
            }      
        }
    };
    /**
     * 保存数据
     * @param options
     * @returns {*}
     */
    let saveData=(type:any, url:any, options?:any,timeout?:number)=>{
        if(type == 'post'){
            return lpost(url, options, timeout);            
        }
        if(type == 'get'){
            return lget(url, options);
        }
    };
    //保存post方法
    function lpost(url: string, options:string, timeout?:number,success?: (data)=>{}, error?: (errorRes)=>{}) {
        return post(url, options,timeout).then(data => {
            console.log('post_return data',data.data)
            if (data.data.hasOwnProperty('data') && !data.data.data) {
                data.data.data = [];
            }
            // console.log('post_return data 111',data.data.data)
            setTimeout(()=>{
                saveFlag.value = 0;
            }, 1000);
            if (success) {
                success(data);
            } else {
                return data;
            }
        }, errorRes => {
            setTimeout(()=>{
                saveFlag.value = 0;
            }, 1000);
            if (error) {
                error(errorRes);
            } else {
                return errorRes;
            }
        })
    };
    //保存 get方法
    function lget(url:string, options?:string, success?: (data)=>{}, error?: (errorRes)=>{}){
        return get(url, options).then(data=>{
            saveFlag.value = 0;
            if (success) {                    
                success(data);
            } else {                  
                return data;
            }
        },errorRes => {
            saveFlag.value = 0;
            if (error) {
                error(errorRes);
            } else {
                return errorRes;
            }
        })
    };

    return {
        firstSave,
        saveData
    }
};
  
export default useSaveFlag;

